// pages/profile/friendInfo/index.ts
import tran from "../../../../utils/language";
import { contactFriend, contactBlacklist } from "../../../../utils/api.js";
import dayjs from "dayjs";
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        homeFriendInfo: {
            type: Object,
            value: {
                userId: "",
                friendStatus: "",
                applyTime: "",
                tagName: "",
                pushName: "",
                applyFriendTipText: "",
                friendSourceInfo: {
                    applyTime: "",
                    friendStatus: "",
                    tagName: "",
                },
            },
            observer(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    this.handleUserInfo(newVal);
                    this.handleData();
                    // this.getFriendAddMsg()
                }
            },
        },
        isFriend: {
            type: Boolean,
            value: false,
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        _t: tran._t("applyFriendPopup"),
        _tBase: tran._t("base"),
        indicatorDots: false,
        vertical: false,
        autoplay: false,
        interval: 2000,
        duration: 500,
        imgList: [
            {
                img: "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                selectFlag: true,
            },
        ],
        selectBtnList: [
            {
                selectFlag: true,
                text: "烹饪",
            },
        ],
        skillList: [
            {
                selectFlag: true,
                text: "数据分析",
                img: "/images/expert.png",
            },
        ],
        langList: [
            {
                selectFlag: true,
                text: "英语",
            },
        ],
        personalityData: [
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
        ],
        popupParams: {
            showPopup: false,
            showType: 0, // 0更新个人资料  1发送好友请求
        },
        sendFlag: true,
        showEventPopup: false,
        confirmPopup: {
            showPopup: false,
            topTitle: tran._t("base").topTitleTip,
            midText: tran._t("base").blockNameTip,
            confirmText: tran._t("base").confirmText,
            closeText: tran._t("base").closeBtnText,
        },
        loginInfo: {},
    },

    /**
     * 组件的方法列表
     */
    methods: {
        tapDot() {
            this.setData({
                showEventPopup: true,
            });
        },
        confirmFn() {
            const { homeFriendInfo } = this.data;
            // 调用 IM 的 API 将用户添加到黑名单
            wx.conn.addUsersToBlocklist({
                //可以添加单个用户 ID 或批量添加多个用户 ID 组成的数组。
                name: [homeFriendInfo.userId],
            });
            this.onCloseEventPopup();
            this.closeFn();
            setTimeout(() => {
                this.joinBlack();
            }, 300);
        },
        closeFn() {
            const { confirmPopup } = this.data;
            confirmPopup.showPopup = false;
            this.setData({
                confirmPopup,
            });
        },
        /**
         * 加入黑名单
         */
        joinBlackName() {
            const { confirmPopup } = this.data;
            confirmPopup.showPopup = true;
            this.setData({
                confirmPopup,
                showEventPopup: false,
            });
        },
        onCloseEventPopup() {
            // const customPopup = this.selectComponent('#event-popup');
            // customPopup && customPopup.hidePopup()
            this.setData({
                showEventPopup: false,
            });
        },
        /**
         * 加入黑名单（我们这边的接口，得先调用im的加入黑名单接口后，再调用此接口）
         */
        joinBlack() {
            const { homeFriendInfo } = this.data;
            const params = {
                tagetUserId: homeFriendInfo.userId,
                flag: true, // true加入黑名单 false移除黑名单
            };
            contactBlacklist(params).then((res: any) => {
                wx.showToast({
                    title: "操作成功",
                });
                this.closeFriend();
            });
        },
        closeFriend() {
            this.triggerEvent("onClose");
        },
        handleData() {
            const { homeFriendInfo, _t } = this.data;
            homeFriendInfo.applyTime =
                homeFriendInfo.friendSourceInfo.applyTime &&
                homeFriendInfo.friendSourceInfo.applyTime != "0"
                    ? dayjs(homeFriendInfo.friendSourceInfo.applyTime).format(
                          "YYYY/MM/DD"
                      )
                    : "-";
            homeFriendInfo.friendStatus =
                homeFriendInfo.friendSourceInfo.friendStatus;
            homeFriendInfo.tagName = homeFriendInfo.friendSourceInfo.tagName;
            let text = "";
            let wantPlay = "";
            if (homeFriendInfo.friendSourceInfo.friendStatus == "2") {
                text = `${homeFriendInfo.pushName} ${_t["thereforeText"]} ${homeFriendInfo.applyTime} ${_t["applyTipText"]}`;
                if (homeFriendInfo.friendSourceInfo.tagName) {
                    wantPlay = `${_t["wantToPlayText"]} ${homeFriendInfo.friendSourceInfo.tagName}`;
                }
            }
            homeFriendInfo.applyFriendTipText = `${text} ${wantPlay || ""}`;
            this.setData({
                homeFriendInfo,
            });
        },
        /**
         * 同意
         */
        agreeTap() {
            const { homeFriendInfo } = this.data;
            wx.conn.acceptContactInvite(homeFriendInfo.userId);
            const params = {
                tagetUserId: homeFriendInfo.userId,
                optionType: "AGREED", // AGREED：同意   REFUSE：拒绝
            };
            contactFriend(params).then((res: any) => {
                this.triggerEvent("agreeAndRefuse", 1);
                getApp().getTotalUnreadCount();
            });
        },
        /**
         * 拒绝
         */
        refuseTap() {
            const { homeFriendInfo } = this.data;
            wx.conn.declineContactInvite(homeFriendInfo.userId);
            const params = {
                tagetUserId: homeFriendInfo.userId,
                optionType: "REFUSE", // AGREED：同意   REFUSE：拒绝
            };
            contactFriend(params).then((res: any) => {
                this.triggerEvent("agreeAndRefuse", 2);
                getApp().getTotalUnreadCount();
            });
        },
        closePopup() {
            this.setData({ popupParams: { showPopup: false, showType: 1 } });
        },
        onClosePopup() {
            const customPopup = this.selectComponent("#custom-popup");
            customPopup && customPopup.hidePopup();
        },
        swiperChange(e: any) {
            console.log(e.detail.current);
            const currentIndex = e.detail.current;
            const { imgList } = this.data;
            imgList.length > 0 &&
                imgList.map((item, index) => {
                    if (index === currentIndex) {
                        item.selectFlag = true;
                    } else {
                        item.selectFlag = false;
                    }
                });
            this.setData({
                imgList,
            });
        },
        handleUserInfo(info: any) {
            let imgList: any = [];
            const { photos, languages } = info;
            photos &&
                photos.length > 0 &&
                photos.map((item: any, index: Number) => {
                    // if (index == 0) {
                    //   item.selectFlag = true
                    // }else {
                    //   item.selectFlag = false
                    // }
                    const obj = {
                        img: item,
                        selectFlag: index == 0 ? true : false,
                    };
                    imgList.push(obj);
                });
            let list: any = [];
            languages.length > 0 &&
                languages.map((item: any) => {
                    if (item.language == "zh_CN") {
                        item.text = "普通话";
                    } else if (item.language == "en_US") {
                        item.text = "英语";
                    }
                    list.push(item);
                });
            this.setData(
                {
                    userInfo: info,
                    imgList,
                    langList: list,
                },
                () => {
                    this.getLoginInfo();
                }
            );
        },
        /**
         * 获取登录的用户的详情
         */
        getLoginInfo() {
            const loginInfo = wx.getStorageSync("userInfo");
            this.setData({
                loginInfo,
            });
        },
        sendChange(e: any) {
            this.setData({
                sendFlag: e.detail,
            });
        },
        changeLangSelect(e: any) {
            const { info } = e.currentTarget.dataset;
            const { langList } = this.data;
            // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
            langList.map((item) => {
                if (item.text === info.text) {
                    item.selectFlag = !item.selectFlag;
                }
            });
            this.setData({
                langList: langList,
            });
        },
        changeSkillSelect(e: any) {
            const { info } = e.currentTarget.dataset;
            const { skillList } = this.data;
            // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
            skillList.map((item) => {
                if (item.text === info.text) {
                    item.selectFlag = !item.selectFlag;
                }
            });
            this.setData({
                skillList: skillList,
            });
        },
        changeSelect(e: any) {
            const { info } = e.currentTarget.dataset;
            const { selectBtnList } = this.data;
            // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
            selectBtnList.map((item) => {
                if (item.text === info.text) {
                    item.selectFlag = !item.selectFlag;
                }
            });
            this.setData({
                selectBtnList: selectBtnList,
            });
        },
        changeIndicatorDots() {
            this.setData({
                indicatorDots: !this.data.indicatorDots,
            });
        },

        changeAutoplay() {
            this.setData({
                autoplay: !this.data.autoplay,
            });
        },

        intervalChange(e: any) {
            this.setData({
                interval: e.detail.value,
            });
        },

        durationChange(e: any) {
            this.setData({
                duration: e.detail.value,
            });
        },
    },
});
